package com.ynwt.service;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.ynwt.constant.JmsDestinationName;
import com.ynwt.domain.User;
import com.ynwt.enums.UserSex;
import com.ynwt.jms.QueueClient;
import com.ynwt.model.BaseResponse;
import com.ynwt.model.ycoin.UpdateInfoRequest;
import com.ynwt.repository.UserDao;
import com.ynwt.util.JsonUtil;
import com.ynwt.util.StringUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;

/**
 * Created by huangying on 2017/6/12.
 */
@Service
public class UserServiceImpl implements UserService {

    private final static Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);


    /**
     * 从微信服务器获取用户信息
     *
     * @param openid
     * @return
     */
    @Override
    public User fetchFromTencent(String openid) {
        LOG.info("method: fetchFromTencent. msg: fetch user from tencent. param: openid: {}", openid);

        GetUserInfoResponse response = userAPI.getUserInfo(openid);
        User user = null;

        if (response != null && response.getSubscribe() != 0) {
            user = new User();
            user.setOpenid(response.getOpenid());
            user.setUnionid(response.getUnionid());
            user.setHeadImgUrl(response.getHeadimgurl());
            //替换昵称中无法存储在mysql中的表情 iPhone的emoji大都有问题
            user.setNickname(StringUtil.filterEmoji(response.getNickname(), "[emoji]"));
            user.setSubscribe(response.getSubscribe());
            user.setSubscribeTime(response.getSubscribeTime());
            user.setCountry(response.getCountry());
            user.setProvince(response.getProvince());
            user.setCity(response.getCity());
            user.setSex(UserSex.valueOfOrdinal(response.getSex()));
            return user;
        }

        LOG.warn("getUserInfoResponse is null.");

        return user;
    }

    /**
     * 更新用户信息
     * @param openid
     * @return
     */
    @Override
    public boolean updateUserInfo(String openid) {

        UpdateInfoRequest request = new UpdateInfoRequest();

        //从腾讯获取用户信息
        User user = fetchFromTencent(openid);

        //设置jms reques消息
        request.setUnionid(user.getUnionid());
        request.setHeadImgUrl(user.getHeadImgUrl());
        request.setOpenid(user.getOpenid());
        request.setCity(user.getCity());
        request.setCountry(user.getCountry());
        request.setProvince(user.getProvince());
        request.setSex(user.getSex().ordinal());
        request.setNickname(user.getNickname());

        BaseResponse response = null;

        //发送jms消息更新逸贝系统用户信息
        try {
            response = JsonUtil.toBean(client.sendAndReceive(request.toString(), JmsDestinationName.UPDATE_INFO, 5000), BaseResponse.class);
        } catch (JMSException e) {
            e.printStackTrace();
        }

        System.out.println(response);

        //如果返回正确，更新微信系统信息
        if (response != null && response.isSuccess()) {
            //找到这个用户，设置新的信息
            User u = userDao.findOne(openid);
            u.setHeadImgUrl(user.getHeadImgUrl());
            u.setSex(user.getSex());
            u.setProvince(user.getProvince());
            u.setCity(user.getCity());
            u.setCountry(user.getCountry());
            u.setNickname(user.getNickname());

            //保存用户信息
            userDao.save(u);
            return true;
        }
        customAPI.sendCustomMessage(openid, new TextMsg("亲爱的环球小伙伴，由于系统繁忙，请过几分钟后再重试哦～"));
        return false;
    }


    @Autowired
    private UserAPI userAPI;

    @Autowired
    private QueueClient client;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CustomAPI customAPI;
}
